package com.qk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.Response.PageResult;
import com.qk.dto.DeptPageDTO;
import com.qk.entity.Dept;
import com.qk.mapper.DeptMapper;
import com.qk.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Override
    public void addDept(Dept dept) {
        if (dept.getName() == null || dept.getName().trim().length() == 0) {
            throw new RuntimeException("部门名称不能为空");
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);
    }
    /**
     * 部门列表分页查询
     * @return
     */
    @Override
    public PageResult<Dept> selectPageDept(DeptPageDTO deptPageDTO) {
        //参数校验
        deptPageDTO.checkPageParam();
        PageHelper.startPage(deptPageDTO.getPage(),deptPageDTO.getPageSize());
        List<Dept> depts = deptMapper.selectPageDept(deptPageDTO.getName(),deptPageDTO.getStatus());
        PageResult<Dept> pageResult = new PageResult<>();
        //PageInfo是PageHelper提供的分页信息类，它包含了分页的各种信息（如总记录数、当前页、总页数等）。
        // 分页查询正确应该是从PageInfo中获取分页的信息和数据再封装到PageResult中。
        // PageInfo对象的getList()方法返回的是当前页的数据列表
        PageInfo<Dept> deptPageInfo = new PageInfo<>(depts);
        pageResult.setTotal(deptPageInfo.getTotal());
        pageResult.setRows(deptPageInfo.getList());
        return pageResult;
    }
    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @Override
    public Dept selectDeptById(Integer id) {
        //参数校验
        if (id == null || id < 1) {
            throw new RuntimeException("id不能为空");
        }
        Dept dept = deptMapper.selectDeptById(id);
        return dept;
    }
    /**
     * 更新部门
     * @param dept
     */
    @Override
    public void updateDept(Dept dept) {
        //参数校验
        if (Objects.isNull(dept)) {
            throw new RuntimeException("部门不能为空");
        }
        //业务处理
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
    /*
    删除部门
      * @param id
     */
    @Override
    public void deleteDeptById(Integer id) {
        //参数校验
        if (id == null || id < 1) {
            throw new RuntimeException("参数错误");
        }
        deptMapper.deleteDeptById(id);
    }

    @Override
    public List<Dept> selectAllDept() {
        List<Dept> depts = deptMapper.selectAllDept();
        return depts;
    }
}